import axios from 'axios';
import { Message, MessageBox } from 'element-ui';

import { getCookie } from '@/utils/support.js';

import store from '../store/index.js';
const apiurl = process.env.VUE_APP_API_URL; //生产环境   开发环境  VUE_APP_API_URL
console.log(apiurl);
console.log(process.env.NODE_ENV); //可以看一下是哪种环境

const service = axios.create({

    baseURL: apiurl + "/index/Api",
    timeout: 60 * 1000
})


service.interceptors.request.use(
    config => {

        config.headers.Authorization = getCookie('token');
        return config;
    },
    err => {
        return Promise.reject(err);
    }
)


service.interceptors.response.use(
    res => {

        const data = res.data;

        if (data.status !== 200) {

            if (data.status == 401) {
                MessageBox.confirm('您的token出错，您是留在这个页面上还是重新登录?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    store.dispatch('LOGOUT_AC');

                    location.reload();

                }).catch(() => {
                    console.log("在原页面");
                });
            } else {
                Message({
                    type: "error",
                    message: data.msg,
                    duration: 2000
                })
            }
        } else {
            return data;
        }
    },
    err => {
        console.log(err);
        Message({
            type: "error",
            message: err,
            duration: 2000
        })
    }
)

// 6.导出
export default service;